package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.service.DeptService;
import com.caifu.util.ShiroUtil;
import com.caifu.util.Util;
import com.caifu.util.Utils;
import com.caifu.vo.DeptDevo;
import com.caifu.vo.DeviceVo;
import com.caifu.vo.UserDeptVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author tww
 * ClassName: DeptServiceImpl.java、
 * createTime: 2020年12月14日 11:34:10
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class DeptServiceImpl implements DeptService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private OrgDeptMapper orgDeptMapper;

    @Resource
    private UserOrgMapper userOrgMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private SysUserMenuMapper sysUserMenuMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public PageInfo<UserDeptVo> getDeptList(String searchParam, Integer currentPage, Integer pageSize, SysUser user) {
        PageHelper.startPage(currentPage, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("searchParam", searchParam);
        params.put("orgId", user.getRelativeId());
        List<UserDeptVo> corgDepts = orgDeptMapper.getDeptList(params);
        PageInfo<UserDeptVo> deptVoPageInfo = new PageInfo<>(corgDepts);
        return deptVoPageInfo;
    }

    @Override
    public Result addOrUpdate(COrgDept cOrgDept, SysUser user) {
        //盐
        String salt = Util.getStringRandom(20);
        //id不为空修改
        if (Utils.isNull(cOrgDept.getId())) {

            //校验账号是否存在
            if (checkUserIdIsExist(cOrgDept.getUserId())) {
                return ResultUtil.success(9999, "账号已存在");
            }

            cOrgDept.setCreateTime(new Date());
            cOrgDept.setStatus("1");
            cOrgDept.setOrgId(user.getRelativeId());
            orgDeptMapper.insert(cOrgDept);

            SysUser sysUser = new SysUser();
            sysUser.setUserId(cOrgDept.getUserId());
            sysUser.setUserPwd(ShiroUtil.sha256("123456", salt));
            sysUser.setUserType("2");
            sysUser.setRelativeId(cOrgDept.getId());
            sysUser.setCreateBy(String.valueOf(user.getId()));
            sysUser.setSalt(salt);
            sysUser.setPaw("123456");
            sysUser.setStatus("1");
            sysUser.setToken("");
            sysUser.setLoginTime(new Date());
            sysUserMapper.insert(sysUser);

            //添加部门菜单
            SysUserMenu sysUserMenu = new SysUserMenu();
            sysUserMenu.setUserNo(sysUser.getId());
            //查询机构菜单
            QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("user_type", "2");
            List<SysMenu> sysMenus = sysMenuMapper.selectList(queryWrapper);
            for (SysMenu sysMenu : sysMenus) {
                sysUserMenu.setMenuNo(sysMenu.getMenuNo());
                sysUserMenuMapper.insert(sysUserMenu);
            }
        } else {
            COrgDept dept = orgDeptMapper.selectById(cOrgDept.getId());
            if (Utils.isNotNull(dept)) {
                dept.setDeptName(cOrgDept.getDeptName());
            }
            SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                    .eq("relative_id", cOrgDept.getId())
                    .eq("status", "1")
                    .eq("user_type", 2));
            if (!sysUser.getUserId().equals(cOrgDept.getUserId())) {
                //校验账号是否存在
                if (checkUserIdIsExist(cOrgDept.getUserId())) {
                    return ResultUtil.success(9999, "账号已存在");
                }
                sysUser.setUserId(cOrgDept.getUserId());
                sysUserMapper.updateById(sysUser);
            }
            orgDeptMapper.updateById(dept);
        }
        return ResultUtil.success(200, "保存成功");
    }


    @Override
    public COrgDept getDeptById(String id) {
        return orgDeptMapper.selectById(id);
    }

    @Override
    public void deleteById(Integer id) {
        COrgDept cOrgDept = orgDeptMapper.selectById(id);
        cOrgDept.setStatus("9");
        //删除部门删除部门账号
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relative_id", id).eq("user_type", 2).eq("status", 1);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        user.setStatus("9");
        orgDeptMapper.updateById(cOrgDept);
        sysUserMapper.updateById(user);

    }

    @Override
    public Result resetPwd(Integer id) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relative_id", id).eq("status", 1).eq("user_type", 2);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if (Utils.isNotNull(user)) {
            //重置密码
            user.setUserPwd(ShiroUtil.sha256("123456", user.getSalt()));
        }
        sysUserMapper.updateById(user);
        return ResultUtil.success(200, "重置成功");
    }

    @Override
    public String getDeptUserId(String id) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relative_id", id).eq("status", 1).eq("user_type", 2);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if (Utils.isNotNull(user)) {
            return user.getUserId();
        }
        return "";
    }

    @Override
    public List<COrgDept> getDeptByUser(SysUser user) {
        List<COrgDept> depts = new ArrayList<>();
        //判断用户类型 1机构 2部门
        String org = "1";
        String dept = "2";
        QueryWrapper<COrgDept> queryWrapper = new QueryWrapper<>();
        if (org.equals(user.getUserType())) {
            queryWrapper.eq("org_id", user.getRelativeId()).eq("status", 1);
            depts = orgDeptMapper.selectList(queryWrapper);
        } else if (dept.equals(user.getUserType())) {
            depts.add(orgDeptMapper.selectById(user.getRelativeId()));
        }
        return depts;
    }

    /**
     * 校验账号是否存在
     */
    public boolean checkUserIdIsExist(String userId) {
        Integer count = sysUserMapper.selectCount(new QueryWrapper<SysUser>()
                .eq("user_id", userId)
                .eq("user_type", 2));
        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> getDeptDevTree(SysUser user) {
        Map<String, Object> map = new HashMap<>();
        List<DeptDevo> deptDevos = new ArrayList<>();
        //判断用户类型
        if ("1".equals(user.getUserType())) {
            //    查询当前用户所有部门
            List<COrgDept> cOrgDepts = orgDeptMapper.selectList(new QueryWrapper<COrgDept>()
                    .eq("org_id", user.getRelativeId())
                    .eq("status", 1));
            if (cOrgDepts.size() > 0) {
                for (COrgDept cOrgDept : cOrgDepts) {
                    DeptDevo deptDevo = new DeptDevo();
                    deptDevo.setId(cOrgDept.getId());
                    deptDevo.setDeptName(cOrgDept.getDeptName());
                    deptDevo.setList(deviceMapper.getDeptDev(cOrgDept.getId()));
                    deptDevos.add(deptDevo);
                }
            }
            map.put("userType", user.getUserType());
            map.put("data", deptDevos);
            COrg org = userOrgMapper.selectById(user.getRelativeId());
            map.put("orgName", org.getOrgName());
        } else if ("2".equals(user.getUserType())) {
            //    获取部门设备
            List<DeviceVo> deptDev = deviceMapper.getDeptDev(user.getRelativeId());
            map.put("userType", user.getUserType());
            map.put("data", deptDev);
        }

        return map;
    }

    @Override
    public Map<String, Object> getDevByDeptNo(SysUser user, Integer deptNo) {
        Map<String, Object> map = new HashMap<>();
        //    获取部门设备
        List<DeviceVo> deptDev = deviceMapper.getDeptDev(deptNo);
        //部门名称
        COrgDept cOrgDept = orgDeptMapper.selectById(deptNo);
        map.put("data", deptDev);
        map.put("deptName", cOrgDept.getDeptName());
        return map;
    }

}
